//
//  HomeTableViewController.swift
//  新浪微博
//
//  Created by mac on 15/11/3.
//  Copyright © 2015年 mac. All rights reserved.
//

import UIKit
import SVProgressHUD
/// 原创微博的可重用 ID
let StatusCellNormalId = "StatusCellNormalId"
/// 转发微博的可重用 ID
let StatusCellRetweetedId = "StatusCellRetweetedId"

class HomeTableViewController: VisitorTableViewController {
    /// 微博数据列表模型
    lazy  var listViewModel = StatusListViewModel()
    
    /// 微博数据数组
    var dataList: [Status]?
    
    override func viewDidLoad() {
        super.viewDidLoad()

        if !UserAccountViewModel.sharedUserAccount.userLogon {
            visitorView?.setupInfo(nil, title: "关注一些人，回这里看看有什么惊喜")
            return
        }
        prepareTableView()
        
        loadData()
        
        
        //监听通知
        NSNotificationCenter.defaultCenter().addObserverForName(WBStatusSelectedPhotoNotification,
            object: nil,
            queue: nil) { [weak self](n) -> Void in
                print("接受通知\(n)")
                guard let urls = n.userInfo?[WBStatusSelectedPhotoURLsKey] as? [NSURL] else{
                    return
                }
                guard let indexPath = n.userInfo?[WBStatusSelectedPhotoIndexPathKey] as? NSIndexPath else {
                    return
                }
                let vc = PhotoBrowserViewController(urls: urls, IndexPath: indexPath)
                
                // 设置 modal 的类型是自定义类型 transition(专场)
                vc.modalPresentationStyle = UIModalPresentationStyle.Custom
                
                //设置转场动画代理
                vc.transitioningDelegate = self?.photoBrowserAnimator
                
                self?.presentViewController(vc, animated: true, completion: nil)
                
        }
    }
    
    deinit {
        //注销通知
        NSNotificationCenter.defaultCenter().removeObserver(self)
        
    }
    
    /// 准备表格
    private func prepareTableView() {
        // 注册可重用 cell

        //取消分割线
        tableView.separatorStyle = .None
        
      ///MARK  -这不太懂 注册可重用 id
        tableView.registerClass(StatusNormalCell.self, forCellReuseIdentifier: StatusCellNormalId)
        tableView.registerClass(StatusRetweetedCell.self, forCellReuseIdentifier: StatusCellRetweetedId)
        // 自动计算行高 - 需要一个自上而下的自动布局的控件，指定一个向下的约束
        //tableView.estimatedRowHeight = 200
        //tableView.rowHeight = UITableViewAutomaticDimension
        tableView.rowHeight = 400
      
        //下拉刷新控件默认没有
        refreshControl = WBRefreshControl()
          //添加监听方法
        refreshControl?.addTarget(self, action: "loadData", forControlEvents: UIControlEvents.ValueChanged)
        
        // 上拉刷新视图
        tableView.tableFooterView = pullupView
    }
    
///加载数据
    func loadData() {
        refreshControl?.beginRefreshing()
        listViewModel.loadStatus(isPullup: pullupView.isAnimating()) { (isSuccessed) -> () in
            
            // 关闭刷新控件
            self.refreshControl?.endRefreshing()
            // 关闭上拉刷新
            self.pullupView.stopAnimating()
            
            if !isSuccessed {
                SVProgressHUD.showInfoWithStatus("加载数据错误，请稍后再试")
                return
            }
            
            //            print(self.listViewModel.statusList)
            
            // 刷新数据
            self.tableView.reloadData()
        }
    }


    // MARK: - 懒加载控件
    /// 上拉刷新提示视图
    private lazy var pullupView: UIActivityIndicatorView = {
       
        let indicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
        indicator.color = UIColor.lightGrayColor()
        
        return indicator
    }()
    //照片浏览转场代理
    private lazy var photoBrowserAnimator = PhotoBrowserAnimator()
    
}
//MARK: - 数据源方法
extension HomeTableViewController {
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return listViewModel.statusList.count
        
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let vm = listViewModel.statusList[indexPath.row]
        
        let cell = tableView.dequeueReusableCellWithIdentifier(vm.cellId, forIndexPath: indexPath) as! StatusCell
        
        cell.viewModel = vm
        
        // 4. 判断是否是最后一条微博
        if indexPath.row == listViewModel.statusList.count - 1 && !pullupView.isAnimating() {
            // 开始动画
            pullupView.startAnimating()
            
            // 上拉刷新数据
            loadData()
            
            print("上拉刷新数据")
        }

        
        return cell
    }
    
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
     
        
        return listViewModel.statusList[indexPath.row].rowHeight

    }
    
}


